import axios, { AxiosHeaders, RawAxiosRequestHeaders } from 'axios'
import { ElMessage } from 'element-plus'
import router from "@/router"
import { logout } from '@/common/index'


const instance = axios.create({
  baseURL: '/api',
  timeout: 5000,
  // headers: { "Authorization": 'Authorization' }

})

instance.interceptors.request.use(
  (config) => {
    // 判断有无token，有则加上
    let token = localStorage.getItem("token");
    if (token) {
      if (config.headers) {
        config.headers["Authorization"] = token;
      }
    }
    return config
  },
  (err) => Promise.reject(err),
)

instance.interceptors.response.use(
  (response) => {
    const data = response.data as IResponse<any>
    // token失效或者超时
    if (data.code === 401) {
      logout(() => { }, () => {
        ElMessage.warning(data.message)
      })
      router.push("/login")
      return
    } else if (data.code !== 200 && data.code !== undefined) {
      ElMessage.warning(data.message)
    }
    return response.data
  },
  (err) => {
    ElMessage.error('请求失败错误信息：' + err.message)
    Promise.reject(err)
  },
)

export default instance
